package com.book.interceptor;

import com.book.permission.CheckPermission;
import com.book.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * @author SuperYu  2024/8/8
 */

public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1：得到目标方法上的注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            boolean f = method.hasMethodAnnotation(CheckPermission.class);
            if (f) {
                // 1-1：
                //有注解，得到访问方法需要权限，
                CheckPermission checkPermission = method.getMethodAnnotation(CheckPermission.class);
                String value = checkPermission.value();
                System.out.println(method.getMethod().getName()+":这个方法需要的权限是："+value);

                String token = request.getHeader("authentication");
                String userName = jwtUtil.parseToken(token);

                // 和自己当前角色的权限去匹配。
                Boolean b = stringRedisTemplate.opsForSet().isMember("permission:" + userName, value);
                if(b){
                    return true;
                }else {
                    throw new RuntimeException("对不起,权限不足！当前方法需要的权限是："+value);
                }
            } else {
                // 1-2：
                //没有注解，放行。说明这个方法没有权限约束
                return true;
            }
        }
        return true;
    }
}
